package idv.loveloser.util;

import java.util.List;

import idv.loveloser.dao.MdlRoleAssignments;
import idv.loveloser.dao.MdlRoleAssignmentsDAO;
import idv.loveloser.dao.MdlRoleCapabilities;
import idv.loveloser.dao.MdlRoleCapabilitiesDAO;
import idv.loveloser.dao.MdlUserDAO;
import idv.loveloser.dao.MdlWebservicesSessions;
import idv.loveloser.dao.MdlWebservicesSessionsDAO;

public class Util {
	private static MdlUserDAO userDAO = new MdlUserDAO();
	private static MdlWebservicesSessionsDAO webServicesSessionDAO = new MdlWebservicesSessionsDAO();
	private static MdlWebservicesSessionsDAO sessionDAO = new MdlWebservicesSessionsDAO();
	private static MdlRoleAssignmentsDAO roleAssignmentDAO= new MdlRoleAssignmentsDAO();
	private static MdlRoleCapabilitiesDAO capabilitiesDAO = new MdlRoleCapabilitiesDAO();
	public static boolean isAuthorised(String client,String sessionKey){
		MdlWebservicesSessions sessions=sessionDAO.findById(Long.parseLong(client));
		try{
			if(sessions.getSessionkey().equals(sessionKey))
				return true;
			else
				return false;
		}catch(NullPointerException npe){
			return false;
		}
		
	}
	public static long getUserId(long client){
		MdlWebservicesSessions selected= webServicesSessionDAO.findById(client);
		return selected.getUserid();
	}
	public static long getRoleId(long userId){
		List<MdlRoleAssignments> roles= roleAssignmentDAO.findByUserid(userId);
		if(roles.size()>0){
			MdlRoleAssignments role = roles.get(0);
			return role.getRoleid();
		}else
			return -1L;
	}
	public static boolean hasCapability(String capStr,long roleId){
		boolean returnBool =false;
		List<MdlRoleCapabilities>caps= capabilitiesDAO.findByRoleid(roleId);
		for(int index=0;index<caps.size();index++){
			MdlRoleCapabilities cap = caps.get(index);
			if(cap.getCapability().equals(capStr))
				returnBool = true;
		}
		return returnBool;
	}
}
